package com.health.institution.service.impl;

import java.util.List;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.health.institution.mapper.DepartmentMapper;
import com.health.institution.domain.Department;
import com.health.institution.service.IDepartmentService;

/**
 * 科室管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-27
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService 
{
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 查询所有一级科室
     */
    @Override
    public List<Department> selectPrimaryDepartments() {
        return departmentMapper.selectPrimaryDepartments();
    }
    
    /**
     * 根据父科室ID查询子科室
     */
    @Override
    public List<Department> selectDepartmentsByParentId(Long parentId) {
        return departmentMapper.selectDepartmentsByParentId(parentId);
    }
    
    /**
     * 查询所有科室（树形结构）
     */
    @Override
    public List<Department> selectDepartmentTree() {
        List<Department> allDepartments = departmentMapper.selectDepartmentTree();
        return buildDepartmentTree(allDepartments);
    }
    
    /**
     * 构建科室树形结构
     */
    private List<Department> buildDepartmentTree(List<Department> allDepartments) {
        List<Department> tree = new ArrayList<>();
        
        // 先找到所有一级科室
        for (Department dept : allDepartments) {
            if (dept.getParentId() == 0 || dept.getParentId() == null) {
                tree.add(dept);
            }
        }
        
        // 为每个一级科室设置子科室
        for (Department parent : tree) {
            parent.setChildren(getChildren(parent.getDepartmentId(), allDepartments));
        }
        
        return tree;
    }
    
    /**
     * 递归获取子科室
     */
    private List<Department> getChildren(Long parentId, List<Department> allDepartments) {
        List<Department> children = new ArrayList<>();
        for (Department dept : allDepartments) {
            if (parentId.equals(dept.getParentId())) {
                children.add(dept);
                // 递归设置子科室的子科室
                dept.setChildren(getChildren(dept.getDepartmentId(), allDepartments));
            }
        }
        return children;
    }
}